package com.rem.concurrency.multithreading.syn;

import lombok.Data;
import lombok.SneakyThrows;

/**
 * 线程安全的购票
 *
 * @author Rem
 * @date 2021-03-04
 */

public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuTicket buTicket = new BuTicket();
        new Thread(buTicket, "zhangsan").start();
        new Thread(buTicket, "lisi").start();
        new Thread(buTicket, "wangwu").start();
    }
}

@Data
class BuTicket implements Runnable {

    private Integer ticket = 10;

    private Boolean flag = true;

    @SneakyThrows
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    //synchronized 保证线程安全
    @SneakyThrows
    synchronized void buy() {
        //判断是否有票
        if (ticket <= 0) {
            flag = false;
            System.err.println("票卖完了");
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket + "张票");
        ticket--;
    }
}